package com.itheima.datastructure.demo1;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MergeSortArray {

    // 合并并去除重复元素
    public static int[] mergeAndRemoveDuplicates(int[] nums1, int[] nums2) {
        List<Integer> mergedList = new ArrayList<>();
        // 将 nums1 中的元素添加到 mergedList
        for (int num : nums1) {
            mergedList.add(num);
        }
        // 将 nums2 中的元素添加到 mergedList
        for (int num : nums2) {
            mergedList.add(num);
        }
        // 对 mergedList 进行排序
        Collections.sort(mergedList);
        // 去除重复元素
        List<Integer> resultList = new ArrayList<>();
        if (!mergedList.isEmpty()) {
            resultList.add(mergedList.get(0));
            for (int i = 1; i < mergedList.size(); i++) {
                if (!mergedList.get(i).equals(mergedList.get(i - 1))) {
                    resultList.add(mergedList.get(i));
                }
            }
        }
        // 将结果存储在一个新的数组中
        int[] result = new int[resultList.size()];
        for (int i = 0; i < resultList.size(); i++) {
            result[i] = resultList.get(i);
        }
        return result;
    }

    // 测试合并并去除重复元素的方法
    public static void testMergeAndRemoveDuplicates() {
        int[] nums1 = {1, 3, 5, 7};
        int[] nums2 = {2, 3, 4, 5, 6};
        int[] result = mergeAndRemoveDuplicates(nums1, nums2);
        System.out.println(Arrays.toString(result));
        // 预期结果
        int[] expected = {1, 2, 3, 4, 5, 6, 7};
        if (Arrays.equals(result, expected)) {
            System.out.println("Test passed!");
        } else {
            System.out.println("Test failed!");
        }
    }

    public static void main(String[] args) {
        testMergeAndRemoveDuplicates();
    }
}